package com.ny.controller;

import com.ny.entity.Devices;
import com.ny.entity.Result;
import com.ny.service.DevicesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/devices")
public class DevicesController {

    @Autowired
    private DevicesService devicesService;
    
    // 6节：查询所有设备数据
    @GetMapping("/findAll")
    public Result findAllDevices(){
        List<Devices> devices = devicesService.findAll();
        return Result.success(devices);
    }
    
    // 6节：根据设备名称查询设备数据
    @GetMapping("/findByName/{name}")
    public Result findDeviceByName(@PathVariable String name){
        List<Devices> devices = devicesService.findByName(name);
        return Result.success(devices);
    }
    
    // 7节：添加一条设备信息
    @PostMapping("/add")
    public Result addDevice(@RequestBody Devices device){
        try {
            Devices addedDevice = devicesService.addDevice(device);
            return Result.success(addedDevice);
        } catch (Exception e) {
            return Result.error("添加设备失败: " + e.getMessage());
        }
    }
    
    // 7节：根据设备id修改设备信息
    @PutMapping("/update/{deviceId}")
    public Result updateDevice(@PathVariable int deviceId, @RequestBody Devices device){
        try {
            Devices updatedDevice = devicesService.updateDevice(deviceId, device);
            if (updatedDevice != null) {
                return Result.success(updatedDevice);
            } else {
                return Result.error("设备不存在");
            }
        } catch (Exception e) {
            return Result.error("更新设备失败: " + e.getMessage());
        }
    }
    
    // 8节：根据设备id删除设备数据
    @DeleteMapping("/delete/{deviceId}")
    public Result deleteDevice(@PathVariable int deviceId){
        try {
            devicesService.deleteDevice(deviceId);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("删除设备失败: " + e.getMessage());
        }
    }
    
    // 8节：根据设备名称模糊查询设备数据
    @GetMapping("/search/{name}")
    public Result searchDevices(@PathVariable String name){
        try {
            List<Devices> devices = devicesService.findByNameContaining(name);
            return Result.success(devices);
        } catch (Exception e) {
            return Result.error("查询设备失败: " + e.getMessage());
        }
    }
}